import logging
import os
from flask import jsonify, Blueprint, g, request, send_from_directory
from flask_pydantic import validate
from common.libs.api_result import ApiResponse
from common import ApiResponse, Result
from common.docx import THESIS_EXPORT_BASE

from .schema import (
    ParamThesisId,
    ParamSaveSingleParagraph,
    ParamSaveDigest,
    SaveNewPara,
    MovePara,
    DeleteParagraph,
    SaveThesisProperty
)
from .service import ThesisServie


LOGGER = logging.getLogger(__name__)
thesis_blueprint = Blueprint("thesis", __name__)


@thesis_blueprint.route("/saveNewParagraph", methods=["POST"])
@validate()
def saveNewParagraph(body: SaveNewPara):
    try:
        body.userId = g.userid
        res: Result = ThesisServie().saveNewPara(body)
        if res.isSucc():
            return ApiResponse().json()
        return ApiResponse(data=[]).error(res.message).json()
    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()


@thesis_blueprint.route("/paragraphMove", methods=["POST"])
@validate()
def paragraphMove(body: MovePara):
    try:
        body.userId = g.userid
        res: Result = ThesisServie().movelPara(body)
        if res.isSucc():
            return ApiResponse(data=res.data).json()
        return ApiResponse(data=[]).error(res.message).json()
    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()
    

@thesis_blueprint.route("/paragraphDelete", methods=["POST"])
@validate()
def paragraphDelete(body: DeleteParagraph):
    try:
        body.userId = g.userid
        res: Result = ThesisServie().deletePara(body)
        if res.isSucc():
            return ApiResponse(data=res.data).json()
        return ApiResponse(data=[]).error(res.message).json()
    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()



@thesis_blueprint.route("/getProgress", methods=["POST"])
@validate()
def getProgress(body: ParamThesisId):
    try:
        body.userId = g.userid
        res: Result = ThesisServie().getProgress(body)
        if res.isSucc():
            return ApiResponse(data=res.data).json()
        return ApiResponse(data=[]).error(res.message).json()
    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()


@thesis_blueprint.route("/getList", methods=["POST"])
@validate()
def getList():
    try:
        res: Result = ThesisServie().getListByUid(g.userid)
        if res.isSucc():
            return ApiResponse(data=res.data).json()
        return ApiResponse().error(res.message).json()

    except Exception as e:
        LOGGER.exception(e)
        return ApiResponse().error(str(e)).json()


@thesis_blueprint.route("/getDetail", methods=["POST"])
@validate()
def detail(body: ParamThesisId):

    body.userId = g.userid
    res: Result = ThesisServie().getDetailById(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    thesis = res.data

    return ApiResponse().set_data(thesis.to_json()).json()


@thesis_blueprint.route("/getOutline", methods=["POST"])
@validate()
def getOutline(body: ParamThesisId):

    body.userId = g.userid
    res: Result = ThesisServie().getOutlineProgressById(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().set_data(res.data).json()


@thesis_blueprint.route("/deleteThesis", methods=["POST"])
@validate()
def deleteThesis(body: ParamThesisId):
    body.userId = g.userid
    res: Result = ThesisServie().deleteThesis(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().json()


@thesis_blueprint.route("/downloadThesis", methods=["POST"])
@validate()
def downloadThesis(body: ParamThesisId):
    body.userId = g.userid
    res: Result = ThesisServie().exportThesis(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().set_data(res.data).json()


@thesis_blueprint.route("/download", methods=["GET"])
def download():
    fileName = request.values.get("fileName")

    fileDir = os.getcwd() + THESIS_EXPORT_BASE
    if not os.path.exists(fileDir + fileName):
        return ApiResponse().error("not found").json()

    return send_from_directory(fileDir, fileName, as_attachment=True)


@thesis_blueprint.route("/saveSingleParagraph", methods=["POST"])
@validate()
def saveSingleParagraph(body: ParamSaveSingleParagraph):
    body.userId = g.userid
    res: Result = ThesisServie().saveSingleParagraph(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().json()


@thesis_blueprint.route("/saveDigest", methods=["POST"])
@validate()
def saveDigest(body: ParamSaveDigest):
    body.userId = g.userid
    res: Result = ThesisServie().saveDigest(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().json()


@thesis_blueprint.route("/saveReference", methods=["POST"])
@validate()
def saveReference(body: SaveThesisProperty):
    body.propName = 'references'
    body.userId = g.userid
    res: Result = ThesisServie().saveThesisProperty(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().json()


@thesis_blueprint.route("/saveThanks", methods=["POST"])
@validate()
def saveThanks(body: SaveThesisProperty):
    body.propName = 'thanks'
    body.userId = g.userid
    res: Result = ThesisServie().saveThesisProperty(body)
    if not res.is_success():
        return ApiResponse().error(res.message).json()

    return ApiResponse().json()
